<?php
	@session_start();
	error_reporting(E_ERROR);  
    ini_set("display_errors","Off");  
	require_once('../user/wxbrower.php');
	require_once("../includes/public.inc.php");
	$sysconfig=mysql_fetch_array(mysql_query("select * from ".DBQIAN."sys_config limit 1"));
	if (!$s)
	{
		echo "该二维码为非法防伪码，购买的产品请谨慎使用!";exit;
		//echo "<script type='text/javascript'>alert('该二维码为非法防伪码，请谨慎使用!');return false;</script>";exit;
	}
	if (!isset($_GET['code']))
	{
		$uwxcode=$_GET['uwxcode'];
		$locaurl=urlencode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&uwxcode=".$uwxcode);//网址解析
		$urls="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".trim($sysconfig['cappid'])."&redirect_uri=".$locaurl."&response_type=code&scope=snsapi_base#wechat_redirect";
		header("Location:".$urls);exit;
	}
	$code = $_GET['code'];//获取code
	$weixin =  file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$sysconfig['cappid']."&secret=".$sysconfig['cappsecret']."&code=".$code."&grant_type=authorization_code");//通过code换取网页授权access_token
	$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
	$array = get_object_vars($jsondecode);//转换成数组
	$openid = $array['openid'];//输出openid
	
	//获取用户微信openid
	//$openid = '1';	//使用单一入口
	function getAccessToken()
	{
		$sysconfig=mysql_fetch_array(mysql_query("select * from ".DBQIAN."sys_config limit 1"));
		 if ($sysconfig['ctokentime'] < time()) {
	      // 如果是企业号用以下URL获取access_token
	      // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
	      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$sysconfig['cappid']."&secret=".$sysconfig['cappsecret'];
	      $res = json_decode(curlGet($url));
	      $access_token = $res->access_token;
	      if ($access_token) {
	        $ctokentime = time() + 7000;
	        $ctoken = $access_token;
			mysql_query("update ".DBQIAN."sys_config set ctoken='$ctoken',
						  ctokentime='$ctokentime', where id=1");
	      }
	    } else {
	      $access_token = $sysconfig['ctoken'];
	    }
	    return $access_token;
	}
	
	function curlGet($url)
	{
		$curl = curl_init();
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	    curl_setopt($curl, CURLOPT_URL, $url);
	
	    $res = curl_exec($curl);
	    curl_close($curl);
	
	    return $res;
	}
	
	$access_token=getAccessToken();//不需要关注公众号，暂时不需要使用这段代码
	$subscribe_msg = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid;
	$subscribe = json_decode(curlGet($subscribe_msg),true);
	$zyxx = $subscribe['subscribe'];
	if($zyxx !== 1)
	{
		header("Location: ../user/guanzhu.php");exit;
	}
?>